package com.dbn.webmagic.pageprocessor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dbn.webmagic.entity.Authorize;
import com.dbn.webmagic.entity.Lincense;
import com.dbn.webmagic.service.AuthorizeService;
import com.dbn.webmagic.service.LincenseService;
import com.dbn.webmagic.utils.FileUtils;
import com.dbn.webmagic.utils.UrlDetail;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import java.io.File;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @Author liheping
 * @Description //品种审定网站数据处理
 * @Date 2021/11/29 15:26
 **/
@Component
public class VarietyPipeline implements Pipeline {
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private LincenseService lincenseService;
    @Value("${IMAGE.BASE.URL}")
    private String baseurl;
    private static String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则
    @SneakyThrows
    @Override
    @Transactional
    public void process(ResultItems resultItems, Task task) {
        String url = resultItems.getRequest().getUrl();
        if(url.contains(UrlDetail.ANNOINFOPIPE_URL)){
            String json=resultItems.get("annoInfo");
            Authorize authorize=new Authorize();
            String annoInfo=json.replaceAll("\\\\","")
                    .replace("[","")
                    .replace("]","");
            String s=annoInfo.substring(1,annoInfo.length()-1);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String tmpname=jsonObject.getString("VarietyName");//品种名称
            String techmainpoint=jsonObject.getString("PlantRequirment");//栽培技术要点
            String plantname=jsonObject.getString("CropID");//作物名称
            String feature=jsonObject.getString("VarietyCharacter");//特征特性
            String output=jsonObject.getString("OutputExpression");//产量表现
            String authidea=jsonObject.getString("JudgementSuggestion");//审定意见
            String authnum=jsonObject.getString("JudgementNo");//审定编号
            String applyname=jsonObject.getString("ApplyCompany");//申请人
            String tmpcome=jsonObject.getString("VarietySource");//品种来源
            String fostername=jsonObject.getString("BreedingCompany");//培育人
            authorize.setTmpname(tmpname);
            authorize.setTechmainpoint(techmainpoint);
            authorize.setPlantname(plantname);
            authorize.setFeature(feature);
            authorize.setOutput(output);
            authorize.setAuthidea(authidea);
            authorize.setAuthnum(authnum);
            authorize.setApplyname(applyname);
            authorize.setTmpcome(tmpcome);
            authorize.setFostername(fostername);
            //添加数据
            QueryWrapper<Authorize> queryWrapper=new QueryWrapper();
            queryWrapper.eq("authnum",authnum);
            authorizeService.add(authorize);
        }
        if(url.contains(UrlDetail.LINCENSEPIPE_URL)){
            String json=resultItems.get("lincense");
            String judgementNo=resultItems.get("judgementNo");
            JSONArray jsonArray=JSONArray.parseArray(json);
            FileUtils fileUtils=new FileUtils();
            for(int i=0;i<jsonArray.size();i++){
                Lincense lincense=new Lincense();
                lincense.setAuthnum(judgementNo);
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String ExpireDate= jsonObject.getString("ExpireDate");
                String IssuingAuthorityCaption= jsonObject.getString("IssuingAuthorityCaption");
                String LicenceNo= jsonObject.getString("LicenceNo");
                String DeputyShow= jsonObject.getString("DeputyShow");
                String ApplyCompanyName= jsonObject.getString("ApplyCompanyName");
                String MainShow= jsonObject.getString("MainShow");
                String ProductionManageCrops=jsonObject.getString("ProductionManageCrops");
                String PublishDate=jsonObject.getString("PublishDate");
                String LicenceID=jsonObject.getString("LicenceID");
                //图片保存路径
                Pattern pat = Pattern.compile(REGEX_CHINESE);
                Matcher mat = pat.matcher(judgementNo);
                String string = mat.replaceAll("");
                String judgenochinese = string.replaceAll(REGEX_CHINESE, "");
                String uuid = UUID.randomUUID().toString().replaceAll("-","").substring(0,18);
                String path = judgenochinese + uuid;

                String zsavePath=File.separator+baseurl+File.separator+"zz"+File.separator+path;
                String fsavePath=File.separator+baseurl+File.separator+"fz"+File.separator+path;
                //下载图片
                File file=new File(zsavePath);
                if(!file.exists()){
                    fileUtils.download(MainShow,LicenceID,zsavePath.trim());
                    fileUtils.download(DeputyShow,LicenceID,fsavePath.trim());
                }
                lincense.setZsavepath(zsavePath);
                lincense.setFsavepath(fsavePath);
                lincense.setApplycompanyname(ApplyCompanyName);
                lincense.setDeputyshow(DeputyShow);
                lincense.setExpiredate(ExpireDate);
                lincense.setIssuingauthoritycaption(IssuingAuthorityCaption);
                lincense.setLicenceno(LicenceNo);
                lincense.setMainshow(MainShow);
                lincense.setProductionmanagecrops(ProductionManageCrops);
                lincense.setPublishdate(PublishDate);
                lincense.setLicenceid(LicenceID);
                QueryWrapper<Lincense> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("licenceid",LicenceID);
                lincenseService.add(lincense);
            }
        }
    }
}
